<?php
namespace app\index\controller;
use app\index\logic\OpenidLogic;

/**
 * 微信api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/05
 * Time: 16:13
 */
class Openid extends Base {

    public function __construct(){
        parent::__construct();
        $this->o_logic = new OpenidLogic();
    }

    /**
     * 保存微信用户
     * @return \think\response\Json
     */
    public function ajax_save_visitor(){
        $params = input();
        $r = $this->check_user_token($params);
        if($r['code'] != 1){
            return json($r);
        }
        $openid = session('openid');

        //检查保存微信用户规则
        $r = $this->o_logic->check_save_visitor_rule($params);
        if(!$r['code']){
            return json($r);
        }

        $maps = [];
        $maps[] = ['openid','=',$openid];
        $v_detail = model('visitor')->get_detail($maps,'id');
        if(empty($v_detail)){
            $v_data['openid'] = $openid;
            $v_data['nickname'] = $params['nickname'];
            $v_data['sex'] = $params['sex'];
            $v_data['city'] = $params['city'];
            $v_data['province'] = $params['province'];
            $v_data['country'] = $params['country'];
            $v_data['language'] = $params['language'];
            $v_data['headimgurl'] = $params['headimgurl'];

            $r_v = model('visitor')->insert($v_data);
        }else{
            $v_data['nickname'] = $params['nickname'];
            $v_data['sex'] = $params['sex'];
            $v_data['city'] = $params['city'];
            $v_data['province'] = $params['province'];
            $v_data['country'] = $params['country'];
            $v_data['language'] = $params['language'];
            $v_data['headimgurl'] = $params['headimgurl'];

            $maps = [];
            $maps[] = ['id','=',$v_detail['id']];
            $r_v = model('visitor')->force()->save($v_data,$maps);
        }

        //写入user表信息
        $r = $this->o_logic->add_user($openid);
        if(!$r['code']){
            return json($r);
        }

        if($r_v !== false){
            return json($this->o_logic->get_response(1,'OK'));
        }
        return json($this->o_logic->get_response(0,'保存失败'));
    }
}